import { AudioClip, AudioSource, Prefab, Sprite, _decorator, assetManager, } from "cc";
import { Logger } from 'db://assets/scripts/utils/log'

const {
  uniquelyReferenced,
  ccclass,
  property,
} = _decorator

@uniquelyReferenced
@ccclass('ResourceManager')
export class ResourceManager {

  @property({
    tooltip: '背景图',
    displayName: '背景图',
    type: Sprite,
  })
  background: Sprite;

  @property({
    tooltip: '点击音效',
    displayName: '点击音效',
    type: AudioClip,
  })
  globalClickClip: AudioClip;

  @property({
      tooltip: '音频播放器',
      displayName: '音频播放器',
      type: AudioSource
  })
  audioSource: AudioSource = null

  #log = new Logger('*ResourceManager*')

  constructor() {
    this.#log.debug('文件管理系统实例化')
  }

  loadPrefab(bundleName: string, prefabPath: string, cb: (prefab?: Prefab) => void) {
    assetManager.loadBundle(bundleName, (e, bundle) => {
      bundle.load(prefabPath, Prefab, ($e, prefab) => {
        if($e) {
          this.#log.error(`加载prefabPath : #${prefabPath}# 加载失败`, $e.message)
          return cb(null)
        }
        cb(prefab)
      })
    })
  }

  loadAudioClip(bundleName: string, audioPath: string, cb: (audioClip?: AudioClip) => void) {
    assetManager.loadBundle(bundleName, (e, bundle) => {
      bundle.load(audioPath, AudioClip, ($e, audioClip) => {
        if($e) {
          this.#log.error(`加载audioPath : #${audioPath}# 加载失败`, $e.message)
        }
        cb(audioClip)
      })
    })
  }
}



export const resourceManager = new ResourceManager();
